package com.apes.autoparts.supplier.jikugroup;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.supplier.platform.*;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.SHA256;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by lishikun on 2021/3/15 11:36
 */
public class JikuGroupApi <T, R> extends SupplierPlatformApi<T, R> {

    private SupplierPlatform supplierPlatform;
    final static String appIdTEST = "jiqunbao_test"; // 测试
    final static String appId = "jiqunbao_prd"; // 生产环境

    // 积准无参构造方法
    JikuGroupApi() {
        super.source = SupplierPlatformConst.JI_KU_GROUP;
    }

    // 同步积准全量数据
    @Override
    public void synTotal(SupplierPlatformItem supplierPlatformItem) {
        if (supplierPlatformItem.getState().equals("debugging")) {
            delete(supplierPlatformItem);
        }
        getStockByPage(supplierPlatformItem, 1, appId);
    }

    private void delete(SupplierPlatformItem supplierPlatformItem) {
        SpringManager.getBean(JiKuGroupDebugRepository.class).deleteBySupplierPlatformItem(supplierPlatformItem.getId());
    }

    // 同步积准增量数据
    @Override
    public void synIncrement(SupplierPlatformItem supplierPlatformItem) {
        getStockByPage(supplierPlatformItem, 2, appId);

    }

    @Override
    public R getProductStock(SimpleRequest request) {
        return null;
    }

    @Override
    public void test(SupplierPlatformItem supplierPlatformItem) {

    }

    // 模拟接口（测试使用）
    @Override
    public void simulationApi(SupplierPlatformItem supplierPlatformItem, JSONObject jo) {

    }

    @Override
    public List<Map> getRowData(SupplierPlatformItem supplierPlatformItem, String source) {
        return null;
    }

    /***
     * 登录获取Token
     */
    public String getToken() {
        long timestamp = new Date().getTime();
        Map param = MapUtil.mapper(
                        "appKey", getSupplierPlatform().getAppKey(),
                        "timestamp", timestamp,
                        "secretKeyDigest", SHA256.getSHA256(String.valueOf(timestamp) + getSupplierPlatform().getAppSecret())
        );
        return resolveError(requestCore(getSupplierPlatform().getUrl() + "v1/token", param, null)).getString("model");
    }

    @Override
    public void handleRow(SimpleRequest request) {

    }

    /**
     * 获取积准供应商
     * @return
     */
    private SupplierPlatform getSupplierPlatform(){
        if (this.supplierPlatform != null) return this.supplierPlatform;

        SupplierPlatform supplierPlatform = SpringManager.getBean(SupplierPlatformRepository.class).findOne(
                JpaDsl.toCriteriaByEq(
                        "code", getSource()
                )
        ).orElse(null);
        if (supplierPlatform == null) throw new RuntimeException("未找到当前平台：" + getSource());

        this.supplierPlatform = supplierPlatform;
        return this.supplierPlatform;
    }

    /**
     * 处理返回值
     */
    private JSONObject resolveError(JSONObject param) {

        if (param.getIntValue("state") != 0 || param.getIntValue("errorCode") != 0) {
            throw new RuntimeException(param.getString("msg"));
        }

        return param;
    }



    /***
     * 获取库存
     */
    private JSONObject getStock(SupplierPlatformItem supplierPlatformItem, String Token, Map param) {

        return resolveError(requestCore(supplierPlatformItem.getSupplierPlatform().getUrl() + "api/v1/parts/queryParts", param,MapUtil.mapper("token", Token)));
    }

    /***
     * 分页获取库存
     */
    private void getStockByPage(SupplierPlatformItem supplierPlatformItem, int queryType, String appId) {
        String Token = getToken();
        // 获取总的分页数
        int page = 0;
        int pageSize = 400;
        Date endTime = new Date();
        Map map = MapUtil.mapper(
                "appKey", supplierPlatformItem.getSupplierPlatform().getAppKey(),
                "appId", appId,
                "queryType",queryType,
                "page", page,
                "size", pageSize,
                "supplierCode", supplierPlatformItem.getAccessKey()
        );
        if (queryType == 2) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startTime = supplierPlatformItem.getSynIncrementTime();
            if (startTime == null) startTime = new Date();
            map.put("startTime", sdf.format(startTime));
            map.put("endTime", sdf.format(endTime));
        }
        JSONObject model = getStock(supplierPlatformItem, Token, map).getJSONObject("model");
        page = model.getIntValue("pages");
        // 循环获取每一页的数据
        JSONArray splitterArray = new JSONArray();
        for (int i = 0; i < page; i++) {
            map.put("page", i);
            JSONObject param = getStock(supplierPlatformItem, Token, map).getJSONObject("model");
            param.put("supplierPlatformItem", supplierPlatformItem.getId());
            if (queryType == 1) model.put("action", "synTotal");
            else param.put("action", "synIncrement");
            if (i +1 == page) param.put("lastData", true);
            if (supplierPlatformItem.getState().equals("debugging")) {
                MQUtil.publish("auto.jiKuGroup.debugging", "积准接口调试数据", param);
//                SpringManager.getBean(DomainService.class).invoke("auto.jiKuGroup.debugging", param);
            } else {
                MQUtil.publish("auto.jiKuGroup.handHeap", "积准接口数据", param);
//                SpringManager.getBean(DomainService.class).invoke("auto.jiKuGroup.handHeap", param);
            }
        }
        if (queryType == 2) {
//            Date now = new Date();
//            Date startDate = DateUtils.addDays(now, -30);
            supplierPlatformItem.setSynIncrementTime(endTime);
            SpringManager.getBean(SupplierPlatformItemRepository.class).save(supplierPlatformItem);
        }
    }

}
